﻿using GSPatEditor.Pat;
using GSPatEditor.Serialization.ProjectSegment;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace GSPatEditor.Serialization
{
    static class PatProjectSerialization
    {
        public static PatProject Deserialization(Stream stream)
        {
            using (var br = new BinaryReader(stream))
            {
                var magic = Encoding.ASCII.GetString(br.ReadBytes(8));
                if (magic != "PAT_PROJ")
                {
                    throw new Exception("Wrong header.");
                }
                var version = br.ReadInt32();
                if (version != 1)
                {
                    throw new Exception("Unsupported version.");
                }

                var proj = new PatProject();
                var bformatter = new BinaryFormatter();

                var segmentCount = br.ReadInt32();
                for (int i = 0; i < segmentCount; ++i)
                {
                    SegmentBase segment;
                    try
                    {
                        segment = (SegmentBase)bformatter.Deserialize(stream);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Pat segment reading error.", ex);
                    }
                    segment.AddToProject(proj);
                }

                return proj;
            }
        }
    }
}
